package model;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedList;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import data.Game;

@Path("/game")
public class GameService {
	
	public static final String PATH = "../data/DATA_game";
	public static final String PATH_TMP = "../data/DATA_game_tmp";
	
	@GET
	@Path("/")
	@Produces({MediaType.APPLICATION_XML})
	public LinkedList<Game> getList() {
		LinkedList<Game> games = new LinkedList<Game>();
		Game pl = null;
		try {
			BufferedReader fichier = new BufferedReader(new FileReader(GameService.PATH));
			String chaine = "";
			while ((chaine = fichier.readLine()) != null && !chaine.isEmpty()) {
				String[] g = chaine.split(",");
				pl = new Game(Integer.parseInt(g[0]), Integer.parseInt(g[1]), Integer.parseInt(g[2]));
				games.add(pl);
			}
			fichier.close();
		} catch (FileNotFoundException e) {
			
		} catch (IOException e) {
			
		}
		return games;
	}
	
	@GET
	@Path("/{idgame}")
	@Produces({MediaType.APPLICATION_XML})
	public Game getGamae(@PathParam("idgame") Integer id) {
		return GameService.getById(id);
	}
	
	@GET
	@Path("/add/{nbplayers}/{status}")
	public Game save(@PathParam("nbplayers") Integer nbplayers, @PathParam("status") Integer status) {
		Game g = new Game();
		try {
			PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(GameService.PATH, true)));
			g.setId(this.getList().size()+1)
			 .setNbPlayers(nbplayers)
			 .setStatus(status);
			out.println(g.getId()+","+g.getNbPlayers()+","+g.getStatus());
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return g;
	}
	
	public static Game getById(Integer id) {
		Game g = new Game();
		try {
			BufferedReader file = new BufferedReader(new FileReader(GameService.PATH));
			String s = "";
			while ((s = file.readLine()) != null && g.getId() == null) {
				String[] l = s.split(",");
				if (Integer.parseInt(l[0]) == id) {
					g = new Game(Integer.parseInt(l[0]), Integer.parseInt(l[1]), Integer.parseInt(l[2]));
				}
			}
			file.close(); 
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return g;
	}

}
